<template>
    <view>
        <div v-if="metadata.options.styleType=='label'" class="x-checkbox-label">
            <span :class="[readOnly?'x-checkbox-span-readOnly':'x-checkbox-span']" @click="labelChange(item,index)" :style="item.checked?styleName(item.value):''" v-for="(item,index) in getLocalData()" :key="item.value">{{ item.label }}</span>
        </div>
        <div v-else style="display: flex;grid-gap: 0.5rem;align-items: center;flex-wrap: wrap">
            <checkbox-group @change="onChange($event,index)"  v-for="(item,index) in getLocalData()" :key="item.value">
                <label>
                    <checkbox :value="item.value" :checked="item.checked" :disabled="readOnly || isDisabled(item)">{{item.label}}</checkbox>
                </label>
            </checkbox-group>
        </div>
    </view>
</template>

<script>
/**
 * 复选框
 */
import MForm from "../js/MForm";
import BaseComplex from "../js/BaseComplex";
import Util from "@/js/Util.js";
export default {
    name: "MCheckbox",
    mixins: [MForm, BaseComplex],
    props: {},
    computed: {
        valMode() {
            //单双值
            return this.metadata.options.valMode || "single";
        },
        ctlType() {
            return this.metadata.options.ctlType || "checkbox";
        },
        isDisabled(){//控件的禁用；（单选控件，复选控件，下拉选择器）
            return (item)=>{
                if(!item){
                    return false
                }
                let disabledCondition = item.disabledCondition ;
                if(disabledCondition && disabledCondition.trim()){
                    if(disabledCondition.indexOf('return') == -1){
                        disabledCondition = 'return ' + item.disabledCondition ;
                    }
                    let func = new Function('row',disabledCondition);
                    return func.call(this.formVm,this.data);
                }
                return false ;
            }
        },
    },
    data() {
        return {
            curValue:[]
        }
    },
    created() {
        let self_=this;
        this.initDataSource(function(){
            self_.initVal(true);
        });
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"componentsLang",key);
        },
        /**
         * 初始化设置值
         * @param  isInit 初始化
         */
        initVal(isInit) {
            let _type = this.ctlType;
            let thisValue=this.value;
            //多选框
            if (_type == "checkboxList") {
                if (!Util.isEmpty(thisValue)) {
                    let _valMode = this.valMode;
                    let _value = ""
                    if (_valMode == "double") {
                        if (!thisValue.includes('{') && !thisValue.includes('}') && isInit) {
                            thisValue=this.setDefaultValue(thisValue);
                            this.updateValue(thisValue)
                            //触发初始化事件
                            this.executeInitCustomQuery(thisValue);
                        }
                        //双值
                        _value = JSON.parse(thisValue).value;
                    } else {
                        //单值
                        _value = thisValue
                    }
                    if (!_value) {
                        _value = '';
                    }
                    this.curValue=_value.split(",");
                } else {
                    this.curValue = [];
                }
                if(!isInit){
                    //处理自定义查询关联字段
                    this.handFieldMapping(this.curValue);
                }
            }
            else{
                this.setSingleData(thisValue);
            }
        },
        /**
         * 单选控件值回填.
         * @param   {Boolean|String} val   - 回填的值.
         */
        setSingleData(val) {
            let trueVal = this.metadata.options.singleCheck.trueVal || true;
            let falseVal = this.metadata.options.singleCheck.falseVal || false;
            if (trueVal && trueVal === val) {
                this.curValue = [true];
            } else if ((falseVal || falseVal === false ) && falseVal === val) {
                this.curValue = [false];
            }else if(['true','false'].includes(val)){
                let value =JSON.parse(val);
                this.curValue = [value]
            }
            if(this.curValue[0]){
                this.updateValue(trueVal);
            }else {
                this.updateValue(falseVal);
            }
        },
        onChange(e,index){
            //当前复选框值
            let checkbox = e.detail.value;
            this.initChange(checkbox,index);
        },
        /**
         * 将数据构建成["value1","value2"]
         * */
        getCheckboxValue(checkbox,index){
            let value = Util.deepClone(this.curValue);
            let options = this.getLocalData();
            let checkboxValue = options[index].value;
            //单一复选 需要将“true”转为true
            if(this.ctlType=='checkbox'){
                checkboxValue = JSON.parse(checkboxValue);
            }
            //有 则表示是选中
            if(checkbox && checkbox.length>0){
                value.push(checkboxValue);
            }else {
                for (let i = 0; i < value.length; i++) {
                    if (value[i] == checkboxValue) {
                        value.splice(i,1);
                        break;
                    }
                }
            }
            return value;
        },
        updateVal(val) {
            //多选框控件值变化
            let _Json = {label: [], value: []};
            let options=this.getOptions();
            if (this.valMode == "double") {
                //双值；
                if (options.length <= 0) {
                    return;
                }
                options.forEach((item, index) => {
                    for (let i = 0; i < val.length; i++) {
                        let _val = val[i];
                        if (item.value == _val) {
                            _Json.label.push(item.label);
                            _Json.value.push(_val);
                        }
                    }
                })
                _Json.label = _Json.label.join(",");
                _Json.value = _Json.value.join(",");
                if (_Json.value == '' || !_Json) {
                    _Json = ''
                }
                _Json = JSON.stringify(_Json);
            } else {
                _Json = val.join(",");
            }
            this.curValue = val;
            if (val == "" || val.length == 0) {
                this.setData('');
            } else {
                this.setData(_Json);
            }
        },
        getLocalData(){
            if(this.ctlType=='checkboxList'){
                let options = this.getOptions();
                if(this.curValue && options){
                    for (let i = 0; i < this.curValue.length; i++) {
                        for (let j = 0; j < options.length; j++) {
                            if(this.curValue[i] == options[j].value){
                                options[j].checked = true;
                                break;
                            }
                        }
                    }
                }
                return options;
            }else {
                let label=this.i18n('selectionBox','单一选择框')
                if(this.metadata.options.singleCheck && this.metadata.options.singleCheck.label){
                    label=JSON.parse(this.metadata.options.singleCheck.label)[this.language];
                }
                let checked = this.curValue && this.curValue[0]
                return [{"value": 'true',"label": label,checked:checked}];
            }
        },
        /**
         * 初始化时 获取双值模式的默认值
         * @param defaultValue
         * @returns {string|*}
         */
        setDefaultValue(defaultValue){
            if (defaultValue.includes('{') && defaultValue.includes('}')) {
                return defaultValue;
            }
            let val = defaultValue.split(',');
            let labelArr = [],valueArr = [];
            let count = 0 ;
            let options = this.getOptions();
            for (let item of options){
                if(count >= val.length){ break }
                if(val.includes(item.value)){
                    labelArr.push(item.label)
                    valueArr.push(item.value)
                    count += 1 ;
                }
            }
            return JSON.stringify({
                label:labelArr.toString(),
                value:valueArr.toString()
            })
        },
        labelChange(item,index){
            if(this.readOnly){
                return
            }
            //当前复选框值
            item.checked=!item.checked;
            let checkbox=[];
            if(item.checked){
                checkbox = [item.value];
            }
            this.initChange(checkbox,index);
        },
        initChange(checkbox,index){
            let _value = this.getCheckboxValue(checkbox,index);
            if(this.ctlType=='checkboxList'){
                if (this.metadata.options.mutex) {//互斥处理
                    _value = _value.filter(value => {
                        return !this.curValue.includes(value);
                    })
                }
                this.updateVal(_value);
            }else {
                if(_value && _value.length>0){
                    let trueVal = this.metadata.options.singleCheck.trueVal;
                    if(trueVal){
                        this.setData(trueVal);
                    }else {
                        this.setData(true);
                    }
                }
                else{
                    let falseVal = this.metadata.options.singleCheck.falseVal;
                    if(falseVal){
                        this.setData(falseVal);
                    }else {
                        this.setData(false);
                    }
                }
            }
        },
        styleName(value){
            if(!this.metadata.options.labelConfig && !this.metadata.options.labelConfig.bgcolor){
                return
            }
            let labelConfig = this.metadata.options.labelConfig;
            let style = {}
            if(labelConfig.borderStyle){
                style = labelConfig.borderStyle
            }
            style['background'] = labelConfig.bgcolor;
            style['color'] = labelConfig.fgcolor;
            return style

        },
    },
    watch: {
        value:function(val){
            this.initVal();
        },
        options: {
            handler(val) {
                if(val){
                    this.initVal(true);
                }
            },
            deep: true
        }
    },
}
</script>

<style scoped>
.x-checkbox-label{
    display: inline-flex;
    flex-wrap: wrap;
    column-gap: 8px;
}
.x-checkbox-span{
    padding: 2px 10px;
    cursor: pointer;
    border-radius: 5px;
    background: #F5F6F9;
}
.x-checkbox-span-readOnly{
    padding: 2px 10px;
    cursor: pointer;
    border-radius: 5px;
    background: #F5F6F9;
    color: rgba(0, 0, 0, 0.25);
}
.rx-detailed{
    background: rgba(245, 246, 249, 1);
    align-items: center;
    padding: 0 0.5rem;
    border-radius: 4px;
    line-height: 2rem;
}
</style>
